package com.efounder.chat.manager;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;
import android.util.Log;

import com.efounder.chat.R;
import com.efounder.chat.activity.NewFriendsActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.model.ApplyGroupNotice;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.GroupBanSpeakEvent;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.model.SessionOnlineEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.notify.MessageNotificationHelper;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ClearUserUtil;
import com.efounder.chat.utils.GroupAvatarHelper;
import com.efounder.chat.utils.ImJsonObjectParseUtil;
import com.efounder.chat.utils.ImNotificationUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.utilcode.util.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import static com.efounder.chat.utils.ImNotificationUtil.CHANNEL_ID_CONTACTS;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
/**
 * 系统消息处理类
 * 消息类型>100  <200
 */
public class SystemMessageHandleManager {

    private static final String TAG = "MessageHandleManager";
    private static final String TYPE_GROUPAPPLY = "TYPE_GROUPAPPLY";//加群申请，
    private static final String TYPE_FRIENDAPPLY = "TYPE_FRIENDAPPLY";//好友申请

    private GroupAvatarHelper helper;
    private Context context;

    public SystemMessageHandleManager(Context context) {
        this.context = context;
    }

    public SystemMessageHandleManager setHelper(GroupAvatarHelper helper) {
        this.helper = helper;
        return this;
    }



    // todo 2016/10/16 处理系统消息：个人信息修改、群组信息更改、添加好友、解散群组等
    public void dealSystemMessage(IMStruct002 imstruct002) {

        //系统角标消息处理
        if (imstruct002.getMessageChildType() == MessageChildTypeConstant
                .subtype_common_bg_system_notification) {
            CommonBgSystemNotificatonParser.notifyCommonBgUpdata(imstruct002);
            return;
        }
        String json = "";
        try {
            json = imstruct002.getMessage();
            LogUtils.i(TAG, "打印输出系统消息：" + json);
            // {"friendUserId":1,"CMD":"applyAddFriend"}
            JSONObject jsonObject = new JSONObject(json);
//            int friendUserId;
            String CMD = jsonObject.getString("CMD");

            switch (CMD) {
                case "applyAddFriend": {// 申请好友
                    int friendUserId = jsonObject.getInt("friendUserId");
                    String leaveMessage = jsonObject.optString("leaveMessage", "");
                    getFriendInfo(friendUserId, false, leaveMessage);
                    break;
                }
                case "addFriend": {// 对方同意你的好友申请
                    int friendUserId = jsonObject.getInt("friendUserId");
                    String leaveMessage = jsonObject.optString("leaveMessage", "");
                    getFriendInfo(friendUserId, true, leaveMessage);
                    break;
                }
                case "rejectAddFriend": // 对方拒绝你的好友申请
                    rejectAddFriend(jsonObject);
                    break;
                case "rejectAddUserToGroup": // 拒绝加群申请
                    rejectAddGroup(jsonObject);
                    break;
                case "userQuitGroup": {//用户退群
                    int groupId = jsonObject.getInt("groupId");
                    int userId = jsonObject.getInt("groupUserId");
                    WeChatDBManager.getInstance().quitGroup(userId, groupId);
                    SystemInfoService.CHATMAP.remove(groupId);
                    //GroupAvatarUtil.createNewGroupAvatar(getApplicationContext(), groupId);
                    if (userId == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(groupId, StructFactory.TO_USER_TYPE_GROUP);
                        if (chatListItem != null) {
                            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
                            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));
                            // 清除通知栏消息
                            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                            int requestCode = Integer.valueOf(chatListItem.getUserId() + "" + chatListItem.getChatType());
                            notificationManager.cancel(requestCode);
                        }
                    } else {
                        helper.createNewGroupAvatar(groupId);
                    }

                    break;
                }
                case "updateOwnerNoteInGroup": {//群成员修改群昵称的消息
                    int groupId = jsonObject.getInt("groupId");
                    int userId = jsonObject.getInt("userId");
                    String note = jsonObject.getString("note");
                    User tempUser = WeChatDBManager.getInstance().getGroupUserInfo(groupId, userId);
                    tempUser.setOwnGroupRemark(note);
                    tempUser.setOtherGroupRemark(note);

                    WeChatDBManager.getInstance().insertOrUpdateMyGroupUser(groupId, tempUser);

                    break;
                }
                case "deleteGroupUser": {//群主移除群组人员
                    int groupId = jsonObject.getInt("groupId");
                    int userId = jsonObject.getInt("groupUserId");
                    WeChatDBManager.getInstance().quitGroup(userId, groupId);
                    SystemInfoService.CHATMAP.remove(groupId);

                    helper.createNewGroupAvatar(groupId);
                    //TODO 如果userId和登录的用户id相同，删除列表数据
                    if (userId == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(groupId, StructFactory.TO_USER_TYPE_GROUP);
                        if (chatListItem != null) {
                            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
                            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));
                            // 清除通知栏消息
                            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                            int requestCode = Integer.valueOf(chatListItem.getUserId() + "" + chatListItem.getChatType());
                            notificationManager.cancel(requestCode);
                            //如果当前在对话界面 通知聊天界面退出
                            EventBus.getDefault().post(new NotifyChatUIRefreshEvent(NotifyChatUIRefreshEvent.TYPE_EXIT,
                                    (byte) chatListItem.getChatType(), chatListItem.getUserId()));
                        }

                    }
                    break;
                }
                case "addUserToGroup": {//新建群聊系统推送的人员列表
                    final int groupId = jsonObject.getInt("groupId");
                    final int userId = jsonObject.getInt("groupUserId");
                    ApplyGroupNotice notice = new ApplyGroupNotice();
                    notice.setGroupId(groupId);
                    notice.setUserId(userId);
                    notice.setTime(System.currentTimeMillis());
                    notice.setRead(true);
                    notice.setState(ApplyGroupNotice.ACCEPTED);
                    WeChatDBManager.getInstance().updateGroupNotice(notice);//更新群通知消息


                    int newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
                    int groupNoticeCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
                    //EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
                    UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(-2 + "", (byte) 0);

//                GetHttpUtil.getUserInfo(userId, getApplicationContext(), new
//                        GetHttpUtil.GetUserListener() {
//                            @Override
//                            public void onGetUserSuccess(User user1) {
//                                //TODO yqs 插入新成员到数据库
//                                WeChatDBManager.getInstance().insertOrUpdateMyGroupUser(groupId, userId);
//
//                            }
//                        });
                    Group group1 = WeChatDBManager.getInstance().getGroupWithUsers(groupId);
                    if (!group1.isExist()) {
                        GetHttpUtil.getGroupById(context, groupId, null, true);
                    }
                    //如果群存在并且群成员数为0
                    else if (group1 != null && group1.getUsers().size() == 0) {
                        GetHttpUtil.getGroupUsers(context, groupId, new GetHttpUtil.ReqCallBack() {
                            @Override
                            public void onReqSuccess(Object result) {
                                Log.i(TAG, "success---yqs");
                                helper.createNewGroupAvatar(groupId);
                            }

                            @Override
                            public void onReqFailed(String errorMsg) {

                            }
                        });
                    } else if (group1 != null) {
                        User user = WeChatDBManager.getInstance().getOneUserById(userId);
                        if (!user.isExist()) {
                            GetHttpUtil.getUserInfo(userId, context, new GetHttpUtil.GetUserListener() {
                                @Override
                                public void onGetUserSuccess(User user1) {
                                    //TODO yqs 插入新成员到数据库
                                    WeChatDBManager.getInstance().insertOrUpdateMyGroupUser(groupId, userId);
                                    helper.createNewGroupAvatar(groupId);
                                }

                                @Override
                                public void onGetUserFail() {

                                }
                            });
                            return;
                        }
                        WeChatDBManager.getInstance().insertOrUpdateMyGroupUser(groupId, userId);
                        helper.createNewGroupAvatar(groupId);
                    }


                    break;
                }
                case "updateGroup": {//更新群组的消息
                    final int groupId = jsonObject.getInt("groupId");
                    final String groupName = jsonObject.getString("groupName");
                    String avatar = "";
                    if (jsonObject.has("avatar")) {
                        avatar = jsonObject.getString("avatar");
                    }
                    Group group = WeChatDBManager.getInstance().getGroup(groupId, false);
                    if (group != null) {
                        group.setGroupName(groupName);
                        if (!avatar.equals("")) {
                            group.setAvatar(avatar);
                        }
//                    group.setBanSpeak(jsonObject.optInt("noSpeak", 0) == 1);
//                    group.setGroupType(jsonObject.optInt("groupType", 0));
                        WeChatDBManager.getInstance().insertOrUpdateGroup(group);
//                    GetHttpUtil.getGroupById(AppContext.getInstance(),groupId,new
//                            GetHttpUtil.getGroupInfoCallBack() {
//                                @Override
//                                public void onGetGroupInfoSuccess(Group group) {
//                                }
//                            }, true);
                    }
                    ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(groupId, StructFactory.TO_USER_TYPE_GROUP);
                    if (chatListItem != null) {
                        chatListItem.setGroup(group);
                        EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
                    }

                    break;
                }
                case "updateUser": {//更新 好友信息
                    int userId = jsonObject.getInt("userId");
                    String json1 = jsonObject.getString("user");
                    User user = WeChatDBManager.getInstance().getOneUserById(userId);
                    if (user != null) {
                        JSONObject jsonObject1 = new JSONObject(json1);
                        //String remark = user.getReMark();
                        //好友更新个人信息没有remark
                        ImJsonObjectParseUtil.updateUserFromJson(user, jsonObject1);
                        // user.setReMark(remark);

                        if (jsonObject1.has("userType")) {
                            user.setType(Integer.valueOf(jsonObject1.getString("userType")));
                        } else {
                            user.setType(User.PERSONALFRIEND);//好友类型
                        }
                        WeChatDBManager.getInstance().insertUserTable(user);
                        if (user.getType() == User.PUBLICFRIEND) {
                            //应用号好友(更新好友表)
                            user.setReMark(user.getName());
                            WeChatDBManager.getInstance().insertOrUpdateFriendUser(user);
                        }
                        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(user.getId(), 0);
                        if (chatListItem != null) {
                            chatListItem.setUser(user);
                            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
                        }
                    }
                    getOpenPlantUserInfo(user);

                    break;
                }
                case "updatePublic": {//应用号信息更新
//                PansoftDeviceAdminManager.initDPM(this);
//                PansoftDeviceAdminManager.initComponent(this, PansoftDeviceAdminReceiver.class);

                    JSONObject publicUser = jsonObject.getJSONObject("public");
                    //// TODO: 17-8-7 MDM管理待修改
//                String command = publicUser.getString("userName");
//                if (publicUser.getInt("userId")==2307) {
//                    switch (command) {
//                        case "lock":
//                            PansoftDeviceAdminManager.lockScreen();
//                            break;
//                        case "updateInfo":
//                            DeviceInfoManager deviceInfoManager = new DeviceInfoManager(this);
//                            deviceInfoManager.getDeviceInfo();
//                            break;
//                        case "logOut":
//                            EventBus.getDefault().post(new LogoutEvent());
//                            break;
//                        case "0000":
//                            PansoftDeviceAdminManager.resetPassword("");
//                            break;
//                        default:
//                            PansoftDeviceAdminManager.resetPassword(command);
//                            break;
//                    }
//                }
                    User user = new User();
                    user.setId(publicUser.getInt("userId"));
                    user.setType(publicUser.getInt("userType"));
                    user.setName(publicUser.getString("userName"));
                    user.setNickName(publicUser.getString("nickName"));
                    user.setAvatar(publicUser.getString("avatar"));
                    user.setReMark(publicUser.getString("nickName"));
                    WeChatDBManager.getInstance().insertOrUpdateFriendUser(user);
                    ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(user.getId(), 0);
                    if (chatListItem != null) {
                        chatListItem.setUser(user);
                        chatListItem.setName(publicUser.getString("nickName"));
                        EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
                    }

                    break;
                }
                case "deviceLogout":
                    //设备下线
                    EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_OFFLINE));
                    break;
                case "applyAddGroup": {//申请加群的系统消息
                    // {"leaveMessage":"我是song171","groupId":2921,"CMD":"applyAddGroup","userId":200347}
                    int groupId = jsonObject.getInt("groupId");//申请要加入的群号

                    int userId = jsonObject.getInt("userId");//申请加群的人的信息

                    // GroupNotifacationActivity.GROUPNOTICOUNT += 1;
                    User tempUser = WeChatDBManager.getInstance().getOneUserById(userId);
                    Group tempGroup = WeChatDBManager.getInstance().getGroup(groupId, false);
                    final ApplyGroupNotice applyGroupNotice = new ApplyGroupNotice();
                    applyGroupNotice.setUserId(userId);
                    applyGroupNotice.setGroupId(groupId);
                    applyGroupNotice.setRead(false);
                    applyGroupNotice.setState(ApplyGroupNotice.UNACCEPT);
                    applyGroupNotice.setTime(System.currentTimeMillis());
                    applyGroupNotice.setLeaveMessage(jsonObject.optString("leaveMessage", ""));
                    applyGroupNotice.setGroup(tempGroup);

                    if (!tempUser.isExist()) {
                        //该用户在本地不存在
                        GetHttpUtil.getUserInfo(userId, context, new GetHttpUtil.GetUserListener() {
                            @Override
                            public void onGetUserSuccess(User user) {
                                applyGroupNotice.setUser(user);
                                showApplyNotice(applyGroupNotice);
                            }

                            @Override
                            public void onGetUserFail() {

                            }
                        });
                    } else {
                        applyGroupNotice.setUser(tempUser);
                        showApplyNotice(applyGroupNotice);

                    }


                    break;
                }
                case "setGroupMana": {//设置系统管理员的系统消息
                    int groupId = jsonObject.getInt("groupId");
                    int userId = jsonObject.getInt("userId");
                    User user = new User();
                    user.setId(userId);
                    user.setGroupUserType(User.GROUPMANAGER);//为用户设置管理员属性

                    WeChatDBManager.getInstance().insertorUpdateGroupManager(groupId, user);

                    break;
                }
                case "cancelGroupMana": {//取消设置系统管理员的系统消息
                    int groupId = jsonObject.getInt("groupId");
                    int userId = jsonObject.getInt("userId");
                    User user = new User();
                    user.setId(userId);
                    user.setGroupUserType(User.GROUPMEMBER);//为用户设置普通成员属性

                    WeChatDBManager.getInstance().insertorUpdateGroupManager(groupId, user);

                    break;
                }
                case "addUserToPublic": {//fixme 收到关注应用号成功的消息
                    int userId = jsonObject.getInt("userId");
                    int publicId = jsonObject.getInt("publicId");
                    User user = WeChatDBManager.getInstance().getOneUserById(publicId);
                    user.setType(User.PUBLICFRIEND);
                    user.setIsBother(false);
                    user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                    WeChatDBManager.getInstance().insertOfficialNumber(user);
                    ImNotificationUtil.showApplyPublicNotification(user.getId(), context);

                    break;
                }
                case "deleteFriend": {//自己删除好友，其他设备收到推送系统消息
                    //{"friendUserId":54,"CMD":"deleteFriend"}
                    int userId = jsonObject.getInt("friendUserId");
                    ClearUserUtil.deleteUserFromDb(context, userId, (byte) 0);

                    break;
                }
                case "dissolveGroup": {//收到解散群组的消息
                    // {"CMD":"dissolveGroup","groupId":1770,"userId":192}
                    int groupId = jsonObject.getInt("groupId");
                    ClearUserUtil.dissolveGroup(context, groupId);

                    break;
                }
                case "recallMessage": {//收到撤回的系统消息
                    String messageID = jsonObject.optString("messageID", "");
                    JFMessageManager.getInstance().setMessageToRecall(messageID);
                    //通知对话界面刷新
                    NotifyChatUIRefreshEvent event = new NotifyChatUIRefreshEvent();
                    event.getParamMap().put("fromUserId", imstruct002.getFromUserId());
                    event.getParamMap().put("chatType", imstruct002.getToUserType());
                    EventBus.getDefault().post(event);
                    ;
                    break;
                }
                case "inputting": {//收到正在输入中的系统消息
                    //已交给页面自己处理 chatmessagelistener 这个类
                    break;
                }
                case "cancelRecallMessage": {//取消作废消息
                    String messageID = jsonObject.optString("messageID", "");
                    JFMessageManager.getInstance().setMessageToRecall(messageID, false);
                    //通知对话界面刷新
                    EventBus.getDefault().post(new NotifyChatUIRefreshEvent());
                    break;
                }
                case "groupAllUserNoSpeakSet": {//group全员禁言的消息
                    int groupId = jsonObject.optInt("groupId", 0);
                    int noSpeak = jsonObject.optInt("noSpeak", 0);
                    Group group = WeChatDBManager.getInstance().getGroup(groupId, false);
                    if (group.isExist()) {
                        group.setBanSpeak(jsonObject.optInt("noSpeak", 0) == 1);
//                    group.setGroupType(jsonObject.optInt("groupType", 0));
                        WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                    }

                    EventBus.getDefault().post(new GroupBanSpeakEvent(groupId, noSpeak == 1));

                    break;
                }
                case "groupUserNoSpeakSet": {//group单独设置某个人是否禁言
                    int groupId = jsonObject.optInt("groupId", 0);
                    int noSpeak = jsonObject.optInt("noSpeak", 0);
                    int userId = jsonObject.optInt("userId", 0);
                    User tempUser = WeChatDBManager.getInstance().getGroupUserInfo(groupId, userId);
                    tempUser.setGroupBanSpeak(noSpeak == 1);
                    WeChatDBManager.getInstance().insertOrUpdateMyGroupUser(groupId, tempUser);
                    EventBus.getDefault().post(new GroupBanSpeakEvent(groupId, userId, noSpeak == 1));

                    break;
                }
                case "updateGroupType": {//group类型（0不允许自由加群，1允许自由加群）
                    int groupId = jsonObject.optInt("groupId", 0);
                    int groupType = jsonObject.optInt("groupType", 0);
                    Group group = WeChatDBManager.getInstance().getGroup(groupId, false);
                    group.setGroupType(groupType);
                    WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                    break;
                }
                case "updateGroupKey": {//修改群英文名称
                    // {"groupId":3096,"CMD":"updateGroupKey","groupKey":"flyme"}
                    int groupId = jsonObject.optInt("groupId", 0);
                    String groupKey = jsonObject.optString("groupKey", "");
                    Group group = WeChatDBManager.getInstance().getGroup(groupId, false);
                    group.setEnglihName(groupKey);
                    WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                    break;
                }
                case "updateGroupDesc": {//修改群介绍
                    //{"groupDesc":"","groupId":3096,"CMD":"updateGroupDesc"}
                    int groupId = jsonObject.optInt("groupId", 0);
                    String groupDesc = jsonObject.optString("groupDesc", "");
                    Group group = WeChatDBManager.getInstance().getGroup(groupId, false);
                    group.setRecommond(groupDesc);
                    WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                    break;
                }
                case "sessionOnline":
                    //消息列表多设备登录布局上线通知刷新
                    EventBus.getDefault().post(new SessionOnlineEvent(SessionOnlineEvent.TYPE_SESSION_ONLINE));
                    break;
                case "sessionLogout":
                    //消息列表多设备登录布局下线通知刷新
                    EventBus.getDefault().post(new SessionOnlineEvent(SessionOnlineEvent.TYPE_SESSION_ONLINE));
                    break;
                default:

                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //拒绝加群申请
    private void rejectAddGroup(JSONObject jsonObject) {
        //{"rejectUserId":200347,"leaveMessage":"","groupId":3161,"CMD":"rejectAddUserToGroup","applyUserId":192205}
        int applyUserId = jsonObject.optInt("applyUserId");
        int groupId = jsonObject.optInt("groupId");
        String leaveMessage = jsonObject.optString("leaveMessage");
        int rejectUserId = jsonObject.optInt("rejectUserId");
        int myselfId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
        if (rejectUserId == myselfId) {
            //是我拒绝的，无需处理
            return;
        }
        ApplyGroupNotice applyGroupNotice = new ApplyGroupNotice();
        applyGroupNotice.setUserId(applyUserId);
        applyGroupNotice.setGroupId(groupId);
        applyGroupNotice.setRead(false);
        applyGroupNotice.setTime(System.currentTimeMillis());
        applyGroupNotice.setLeaveMessage(leaveMessage);
        if (applyUserId == myselfId) {
            //是我自己，显示被拒绝
            applyGroupNotice.setState(ApplyGroupNotice.REJECTED);
            WeChatDBManager.getInstance().insertOrUpdateGroupNotice(applyGroupNotice);
//            ImNotificationUtil.showApplyGroupNotice(context,
//                    applyGroupNotice, ImNotificationUtil.APPLYING);
            User rejectUser = WeChatDBManager.getInstance().getOneUserById(rejectUserId);
            Group group = WeChatDBManager.getInstance().getGroupInGroups(groupId, false);
            MessageNotificationHelper.notify(AppContext.getInstance(), "申请被拒绝", "您申请加入" + group.getGroupName() + "被" +
                    rejectUser.getNickName() + "拒绝");
            EventBus.getDefault().post(new UpdateBadgeViewEvent("-2", (byte) 0));
        } else {
            //其他管理员设置为已拒绝
            applyGroupNotice.setState(ApplyGroupNotice.REFUSE);
            WeChatDBManager.getInstance().insertOrUpdateGroupNotice(applyGroupNotice);

        }


    }


    //处理拒绝加好友的消息提示
    private void rejectAddFriend(JSONObject jsonObject) throws Exception {
        //{"rejectUserId":192205,"leaveMessage":"","CMD":"rejectAddFriend","applyUserId":200347}
        int rejectUserId = jsonObject.getInt("rejectUserId");
        int applyUserId = jsonObject.getInt("applyUserId");

        if (rejectUserId == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
            //多设备 自己收到不显示，只处理数据库操作
            User applyUser = WeChatDBManager.getInstance().getOneApplyAddFriend(applyUserId);
            if (applyUser != null) {
                applyUser.setState(User.REFUSE);
                applyUser.setIsRead(true);
                WeChatDBManager.getInstance().refuseApplyFriend(applyUser);
            }
            return;
        }
        String leaveMessage = jsonObject.optString("leaveMessage", "");
        String content = leaveMessage.equals("") ? "对方拒绝了您的好友请求" : leaveMessage;
        User applyUser = WeChatDBManager.getInstance().getOneApplyAddFriend(rejectUserId);
        if (applyUser != null) {
            applyUser.setState(User.REJECTED);
            applyUser.setIsRead(false);
            applyUser.setLeaveMessage(content);
            WeChatDBManager.getInstance().refuseApplyFriend(applyUser);
        }
        User otherUser = WeChatDBManager.getInstance().getOneUserById(rejectUserId);
        String text = otherUser.getNickName() + "拒绝了您的好友请求";
        //通知栏提醒
        MessageNotificationHelper.notify(AppContext.getInstance(), text, content);
        UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(-2 + "", (byte) 0);
        EventBus.getDefault().post(updateBadgeViewEvent);
    }


    /**
     * 得到用户信息
     *
     * @param uid          用户id
     * @param isFriend     是好友保存到本地，不是好友，不保存到本地
     * @param leaveMessage 申请验证消息
     */
    public void getFriendInfo(final int uid, final boolean isFriend, final String leaveMessage) {
        EFHttpRequest httpRequest = new EFHttpRequest(context);
        String url = GetHttpUtil.ROOTURL + "/IMServer/user/getOtherUserByUserId?otherUserId=" + uid;
        httpRequest.httpGet(url);
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {

            @Override
            public void onRequestSuccess(int requestCode, String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response).getJSONObject("user");
                    User user = new User();
                    user = ImJsonObjectParseUtil.updateUserFromJson(user, jsonObject);
                    user.setDeptId(0);
                    user.setIsImportantContacts(false);
//                    user.setIsBother(false);
//                    user.setIsTop(false);
                    user.setSortLetters(null);

                    if (isFriend) {
                        user.setState(User.ACCEPTED);//0 未接受好友申请 1，已添加同意好友申请，2已发送好友申请
                        user.setTime(System.currentTimeMillis());
                        user.setIsRead(false);
                        User applyUser = WeChatDBManager.getInstance().getOneApplyAddFriend(user.getId());
                        if (applyUser == null) {
                            applyUser = user;
                        } else {
                            applyUser.setState(User.ACCEPTED);
//                            applyUser.setIsRead(false);
                            applyUser.setIsRead(true);
                            applyUser.setTime(System.currentTimeMillis());
                        }
                        //todo 20180803 屏蔽了显示角标
//                        UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(-2 + "", (byte) 0);
//                        EventBus.getDefault().post(updateBadgeViewEvent);
                        if (WeChatDBManager.getInstance().queryIsFriend(uid)) {
                            //增加这个判断的原因是多设备登录的原因，别的设备同意添加的还有，本设备也必须获取到，这个时候不能弹出通知栏
                            return;
                        }
                        //1存入好友表，2删除自己发起的 好友请求
                        WeChatDBManager.getInstance().agreeNewFriendApply(applyUser);
                        WeChatDBManager.getInstance().deleteApplyFriend(applyUser.getId());
                        //通知栏提示
                        showAddFriendNotification(user, isFriend);

                    } else {
                        //将好友申请保存到数据库
                        user.setState(User.UNACCEPT);
                        user.setIsRead(false);
                        user.setTime(System.currentTimeMillis());
                        user.setLeaveMessage(leaveMessage);
                        WeChatDBManager.getInstance().insertSendNewFriendApply(user);
//
                        int newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
                        int groupNoticeCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
                        //EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
                        UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(-2 + "", (byte) 0);
                        EventBus.getDefault().post(updateBadgeViewEvent);
                        showAddFriendNotification(user, isFriend);
                    }
                    getOpenPlantUserInfo(user);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRequestFail(int requestCode, String message) {
            }
        });

    }

    // 显示添加好友通知
    @SuppressWarnings("deprecation")
    private void showAddFriendNotification(User user, Boolean isFriend) {
        NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        ImNotificationUtil.createNotificationChannel(context);
        // 我们并不需要为 notification.flags 设置 FLAG_ONGOING_EVENT，因为
        // 前台服务的 notification.flags 总是默认包含了那个标志位
        if (!isFriend) {
            Intent intent = new Intent(context, NewFriendsActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(AppContext.getInstance());
            stackBuilder.addParentStack(NewFriendsActivity.class);
            stackBuilder.addNextIntent(intent);
            PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


            long[] vibrate = {0, 100, 200, 300};
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context, CHANNEL_ID_CONTACTS)
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.wechat_icon_launcher))
                            .setTicker(user.getNickName() + " 请求添加您为好友")
                            .setContentTitle("好友申请")
                            .setContentText(user.getNickName()
                                    + " 请求添加您为好友")
                            .setContentIntent(contentIntent)
                            .setDefaults(Notification.DEFAULT_LIGHTS)
                            .setDefaults(Notification.FLAG_SHOW_LIGHTS)
                            .setAutoCancel(true)
                            .setVibrate(vibrate)//设置震动
                            .setLights(0xff00ff00, 300, 1000)
                            .setColor(Color.parseColor("#243BAE"))
                            .setWhen(System.currentTimeMillis());
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher_alpha);
//            } else {
            mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
            //  }
            mNM.notify(0, mBuilder.build());
        } else {
            Intent intent = new Intent(context, NewFriendsActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(AppContext.getInstance());
            stackBuilder.addParentStack(NewFriendsActivity.class);
            stackBuilder.addNextIntent(intent);
            PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

            long[] vibrate = {0, 100, 200, 300};
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context, CHANNEL_ID_CONTACTS)
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.wechat_icon_launcher))
                            .setTicker(user.getNickName() + " 已同意您的好友申请")
                            .setContentTitle("好友申请通过")
                            .setContentText(user.getNickName()
                                    + " 已同意您的好友申请")
                            .setContentIntent(contentIntent)
                            .setDefaults(Notification.DEFAULT_LIGHTS)
                            .setDefaults(Notification.FLAG_SHOW_LIGHTS)
                            .setAutoCancel(true)
                            .setVibrate(vibrate)//设置震动
                            .setLights(0xff00ff00, 300, 1000)
                            .setColor(Color.parseColor("#243BAE"))
                            .setWhen(System.currentTimeMillis());
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher_alpha);
//            } else {
            mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
            //    }
            mNM.notify(0, mBuilder.build());
        }

    }

    private void showApplyNotice(ApplyGroupNotice applyGroupNotice) {
        WeChatDBManager.getInstance().insertOrUpdateGroupNotice(applyGroupNotice);
        ImNotificationUtil.showApplyGroupNotice(context,
                applyGroupNotice, ImNotificationUtil.APPLYING);
        EventBus.getDefault().post(new UpdateBadgeViewEvent("-2", (byte) 0));
    }

    //获取星际通讯用户相关信息
    private void getOpenPlantUserInfo(final User user) {
        if (!EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                .getString(R.string.special_appid))) {
            return;
        }
        if (user.getType() == User.PUBLICFRIEND) {
            //应用号无需请求数据
            return;
        }
        OpenEthRequest.getUserEthByImUserId(context, user.getId(), new OpenEthRequest.EthUserRequestListener() {
            @Override
            public void onSuccess(User user1) {
                user.setWalletAddress(user1.getWalletAddress());
                user.setPublicKey(user1.getPublicKey());
                user.setRSAPublicKey(user1.getRSAPublicKey());
                user.setWeixinQrUrl(user1.getWeixinQrUrl());
                user.setZhifubaoQrUrl(user1.getZhifubaoQrUrl());

                WeChatDBManager.getInstance().insertUserTable(user);
            }

            @Override
            public void onSuccess(String ethAddress, String publicKey, String RSAPublicKey) {
//                user.setWalletAddress(ethAddress);
//                user.setPublicKey(publicKey);
//                user.setRSAPublicKey(RSAPublicKey);
//                WeChatDBManager.getInstance().insertUserTable(user);
            }

            @Override
            public void onFail(String error) {

            }
        }, true);
    }
}
